package EVO.controller;

import EVO.entity.Student;
import EVO.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String strId = request.getParameter("id");
        String strName = request.getParameter("name");
        String strEmail = request.getParameter("email");
        String strAge = request.getParameter("age");


        WebApplicationContext wlc = null;
        //获取ServletContext中的容器对象，创建好的容器对象，拿来就用
        /*
        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
        Object attr = getServletContext().getAttribute(key);
        if(attr != null){
            wlc = (WebApplicationContext)attr;
        }
        */
        //使用框架中的方法，获取容器对象
        ServletContext sc = request.getServletContext();
        wlc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        StudentService studentService = (StudentService) wlc.getBean("studentService");
        Student stu = new Student(Integer.valueOf(strId),strName,strEmail,Integer.valueOf(strAge));
        studentService.addStudent(stu);

        request.getRequestDispatcher("/result.jsp").forward(request,response);
    }

}
